package com.net.oil.oilWear;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import
androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.net.oil.R;
import com.net.oil.app.Constant;
import com.net.oil.base.BaseActivity;
import com.net.oil.oilWear.adapter.FillOilRecordRecyclerViewAdapter;
import com.net.oil.oilWear.bean.FillOilRecordBean;
import com.net.oil.oilWear.contract.FillOilRecordContract;
import com.net.oil.oilWear.presenter.FillOilRecordPresenter;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FillOilRecordActivity extends BaseActivity<FillOilRecordPresenter> implements FillOilRecordContract.View {

    public static final String IntentCarId = "intent_car_id";
    public static final int editRequestCode = 11;

    @BindView(R.id.toolbar_go_back)
    ImageView toolbarGoBack;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    private int carId = -1;

    private int page = 1;           //当前页
    private boolean haveMore = false;

    private FillOilRecordRecyclerViewAdapter adapter;
    private int longClickPosition = -1;

    private boolean isDeleate = false;      //是否删除记录，如果删除，返回前一个界面需要更新数据

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fill_oil_record);
        ButterKnife.bind(this);
        presenter = new FillOilRecordPresenter(this);
        carId = getIntent().getIntExtra(IntentCarId, -1);
        initView();
        if (carId != -1){
            presenter.getFillOilRecord(carId, 1);
        }

    }

    private void initView() {
        toolbarTitle.setText(getString(R.string.fill_oil_record));

        adapter = new FillOilRecordRecyclerViewAdapter(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new FillOilRecordRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemLongClickListener(int position, int recordId) {
                showRemoveItemDialog(recordId);
                longClickPosition = position;
            }

            @Override
            public void onItemClickListener(FillOilRecordBean.ListBean listBean) {
                onItemClick(listBean);
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1) && haveMore && page > 1) {
                    recyclerView.post(new Runnable() {
                        @Override
                        public void run() {
                            adapter.changeMoreStatus(Constant.LOADING_MORE);
                        }
                    });
                    presenter.getFillOilRecord(carId, page);
                }
            }
        });
    }

    private void onItemClick(FillOilRecordBean.ListBean listBean) {
        Intent intent = new Intent(this, AddOilWearActivity.class);
        Bundle bundle = new Bundle();
        bundle.putInt(AddOilWearActivity.IntentType, AddOilWearActivity.EDIT);
        bundle.putSerializable(AddOilWearActivity.IntentRecord, listBean);
        intent.putExtras(bundle);
        startActivityForResult(intent, editRequestCode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK){
            if (requestCode == editRequestCode){
                if (carId != -1){
                    page = 1;
                    presenter.getFillOilRecord(carId, 1);
                }
            }
        }
    }

    @OnClick({R.id.toolbar_go_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.toolbar_go_back:
                closeActivity();
                break;
        }
    }

    private void closeActivity(){
        if (isDeleate){
            setResult(RESULT_OK);
        }
        finish();
    }

    /**
     * 获取加油记录成功
     * @param fillOilRecordBean     加油记录
     */
    @Override
    public void getFillOilRecordSuccess(FillOilRecordBean fillOilRecordBean) {
        if (fillOilRecordBean != null){
            if (fillOilRecordBean.getList() != null && fillOilRecordBean.getList().size() > 0){
                if (page == 1) {
                    adapter.updateList(fillOilRecordBean.getList());
                } else if (page > 1) {
                    adapter.loadMore(fillOilRecordBean.getList());
                }
                adapter.changeMoreStatus(Constant.PULL_LOAD_MORE);
                haveMore = true;
                page++;
            }else {
                adapter.changeMoreStatus(Constant.LOADING_NONE);
                haveMore = false;
            }
        }
    }

    /**
     * 获取加油记录失败
     */
    @Override
    public void getFillOilRecordFailed() {

    }

    /**
     * 删除加油记录成功
     */
    @Override
    public void deleteFillOilRecordSuccess() {
        dismissProgressDialog();
        isDeleate = true;
        if (longClickPosition != -1){
            adapter.removeItem(longClickPosition);
        }
    }

    /**
     * 删除加油记录失败
     */
    @Override
    public void deleteFillOilRecordFailed() {
        dismissProgressDialog();
    }

    private void showRemoveItemDialog(final int recordId){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确定删除该记录？");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                presenter.deleteFillOilRecord(recordId);
                showProgressDialog();
            }
        });
        builder.show();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK){
            closeActivity();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
